<template>
    <!-- pages/discovery/discovery.wxml -->

    <view class="containView">
        <scroll-view :scroll-x="true" class="nav" :scroll-left="navScrollLeft" :scroll-with-animation="true">
            <block v-for="(navItem, idx) in navData" :key="idx">
                <view :class="'nav-item ' + (currentTab == idx ? 'active' : '')" :data-current="idx" @tap="switchNav">
                    <text>{{ navItem.name }}</text>
                    <view class="active_index" v-if="currentTab == idx"></view>
                </view>
            </block>
        </scroll-view>

        <view class="messageList borderShowdow">
            <view class="easyTalkNav">
                <block v-for="(item, index) in easyNav" :key="index">
                    <view :class="'easyTalkNavItem  ' + (order == index ? 'easyTalkActive' : '')" :id="index" @tap="navClick">{{ item.name }}</view>
                </block>
            </view>

            <block v-for="(cellItem, cellIdx) in datalist" :key="cellIdx">
                <view class="classCell" :id="cellIdx" @tap="cellClick">
                    <view>
                        <image class="class-cell-avatar" :src="cellItem.author ? cellItem.avatar : userAvatar + '0'"></image>
                    </view>

                    <view class="class-cell-contentView">
                        <view class="username">
                            {{ member_nickname ? member_nickname : cellItem.author ? cellItem.author : '匿名' }}
                        </view>
                        <view class="message">
                            <text class="special" v-if="cellItem.special != 0 && cellItem.special != 2 && cellItem.special != 5">
                                <block v-if="cellItem.special == 1">投票</block>
                                <block v-if="cellItem.special == 2">商品</block>
                                <block v-if="cellItem.special == 3">悬赏</block>
                                <block v-if="cellItem.special == 4">活动</block>
                                <block v-if="cellItem.special == 5">辩论</block>
                            </text>
                            {{ cellItem.subject }}
                        </view>

                        <rich-text class="class-cell-time" :nodes="cellItem.dateline"></rich-text>
                        <view class="toolRight">
                            <view class="shareHidden borderShowdow" v-if="cellItem.shareshow == 1">
                                <button open-type="share" :plain="true" @tap.stop.prevent="listShare" :id="cellIdx">
                                    <image class="shareIcon" :src="minImgDoc + 'workshare.png'"></image>
                                </button>
                                <button :plain="true" @tap.stop.prevent="disVoice" :id="cellIdx">
                                    <image class="shareIcon" :src="minImgDoc + 'workvoice.png'"></image>
                                </button>
                            </view>
                            <image src="" class="discIcon" :src="minImgDoc + 'cpostmessage.png'" @tap.stop.prevent="discClick" :data-tid="cellItem.tid" :id="cellIdx"></image>
                        </view>
                    </view>
                </view>
            </block>
            <view class="emptyView" v-if="datalist.length == 0">
                <view style="width: 100%; height: 10rpx"></view>
                <image :src="minImgDoc + 'emptyIcon.png'"></image>
                <view class="emptyMsg">
                    <block v-if="currentTab == 0">还没有内容被推荐</block>
                    <block v-else>最近没有新内容推荐</block>
                    <!-- 赶紧去<text catchtap='postEnter'>发布</text>吧 -->
                </view>
            </view>
        </view>
        <view class="noMoreView">别再用力了，你已经滑到底啦</view>

        <video id="detailVideo" :class="fullScreen ? 'show' : 'hide'" :autoplay="true" @play="playVideo" @fullscreenchange="fullScreenChange" :src="currentVideo"></video>
    </view>
</template>

<script>
// pages/discovery/discovery.js
const newestUrl = require('../../config').newestUrl;

const digestUrl = require('../../config').digestUrl;

const minImgDoc = require('../../config').minImgDoc;

const userAvatar = require('../../config').userAvatar;

const checkUrl = require('../../config').checkUrl;

const util = require('../../utils/util.js');

var event = require('../../utils/event.js');

const app = getApp();

export default {
    data() {
        return {
            minImgDoc: minImgDoc,
            userAvatar: userAvatar,
            userInfoHidden: true,
            fullScreen: false,
            datalist: [],

            navData: [
                {
                    name: '最新'
                },
                {
                    name: '精华'
                }
            ],

            currentTab: 0,
            page: 1,
            currentVideo: '',
            is_moving_slider: false,
            currentAudio: '',
            navScrollLeft: 0,

            navItem: {
                idx: '',
                name: ''
            },

            easyNav: [],
            order: '',

            cellItem: {
                cellIdx: '',
                author: false,
                avatar: '',
                special: 0,
                attachlist: [],

                videoA: [
                    {
                        attachment: ''
                    }
                ],

                imageA: [],
                audioA: '',
                dateline: '',
                shareshow: 0,
                tid: ''
            },

            cellIdx: 0,
            member_nickname: false,
            aidx: 0,

            attItem: {
                aid: '',
                thumb: ''
            },

            video: {
                aid: '',
                attachment: ''
            },

            audio: {
                aid: ''
            },

            is_play: '',
            attachment: '',
            listIndex: [],
            current_process: [],
            total_process: '',
            slider_max: '',
            slider_value: ''
        };
    },
    onLoad: function (options) {
        if (options.shareid) {
            // 从分享进入帖子详情页
            var item = {
                tid: options.shareid,
                special: options.special ? options.special : 0
            };
            this.toDetail(item);
        }

        uni.showLoading();
        this.requestData();
        this.setupAudioPlayer();
        this.allowpostcomment();
    },
    onReady() {
        this.videoContext = uni.createVideoContext('detailVideo');
    },
    onUnload: function () {
        this.innerAudioContext.destroy();
    },
    onPullDownRefresh: function () {
        this.page = 1;
        this.requestData();
    },
    onReachBottom: function () {
        this.page++;
        this.requestData();
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        var title = '站长之家论坛';
        var imagePath = minImgDoc + '/static/pages/discovery/kehoushare.png';
        var path = '/pages/discovery/discovery';
        return {
            title: title,
            path: path,
            imageUrl: imagePath
        };
    },
    methods: {
        allowpostcomment: function () {
            var url = checkUrl;
            app.globalData.apimanager
                .getRequest(url)
                .then((res) => {
                    var repliesrank = res.setting.repliesrank;
                    var allowpostcomment = res.setting.allowpostcomment;
                    app.globalData.repliesrank = repliesrank;
                    app.globalData.allowpostcomment = allowpostcomment;
                })
                .catch((res) => {});
        },

        switchNav(event) {
            var cur = event.currentTarget.dataset.current;

            if (this.currentTab != cur) {
                this.currentTab= cur;
            }

            this.page = 1;
            this.requestData();
        },

        requestData() {
            var url = newestUrl;

            if (this.currentTab == 1) {
                url = digestUrl;
            }

            var data = {
                page: this.page
            };
            app.globalData.apimanager
                .getRequest(url, data)
                .then((res) => {
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    var datalist = res.Variables.data ? res.Variables.data : [];

                    for (let i = 0; i < datalist.length; i++) {
                        let postItem = datalist[i];
                        var listindex = i + this.datalist.length; // 附件处理

                        let attachlist = postItem.attachlist;
                        let imageA = [];
                        let audioA = [];
                        let videoA = [];
                        let DownloadA = [];

                        for (let aidKey in attachlist) {
                            let attItem = attachlist[aidKey];
                            let newUrl = attItem.attachment;
                            attItem['newUrl'] = newUrl;

                            if (attItem.type == 'image') {
                                imageA.push(attItem);
                            } else {
                                if (attItem.type == 'audio') {
                                    let total_process = '00:00';

                                    if (attItem.description) {
                                        total_process = util.formatTime(parseInt(attItem.description));
                                    }

                                    attItem['toolUse'] = {
                                        attachment: newUrl,
                                        listIndex: listindex,
                                        total_process: total_process
                                    }; // console.log(attItem);

                                    audioA.push(attItem);
                                } else {
                                    if (attItem.type == 'video') {
                                        videoA.push(attItem);
                                    } else {
                                        if (
                                            attItem.ext == 'pdf' ||
                                            attItem.ext == 'ppt' ||
                                            attItem.ext == 'pptx' ||
                                            attItem.ext == 'docx' ||
                                            attItem.ext == 'doc' ||
                                            attItem.ext == 'xls' ||
                                            attItem.ext == 'xlsx'
                                        ) {
                                            DownloadA.push(attItem);
                                        }
                                    }
                                }
                            }
                        }

                        postItem['imageA'] = imageA;
                        postItem['audioA'] = audioA;
                        postItem['videoA'] = videoA;
                        postItem['DownloadA'] = DownloadA;
                    }

                    if (this.page > 1) {
                        datalist = this.datalist.concat(datalist);
                    }

                    this.datalist= datalist;
                })
                .catch((res) => {
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                });
        },

        cellClick(e) {
            var item = this.datalist[e.currentTarget.id];
            this.toDetail(item);
        },

        toDetail(item) {
            var special = item.special;
            var tid = item.tid;
            var url = '../thread_detail/thread_detail?tid=';

            if (special == 1) {
                url = '../questionnaire_detail/questionnaire_detail?tid=';
            } else {
                if (special == 3) {
                    url = '../question_answer_detail/question_answer_detail?tid=';
                } else {
                    if (special == 4) {
                        url = '../activity_detail/activity_detail?tid=';
                    }
                }
            }

            url += tid;
            uni.navigateTo({
                url: url
            });
        },

        // 播放视频 -------------------
        clickVideo(e) {
            this.currentVideo= e.currentTarget.id;
            this.videoContext.play();
            this.videoContext.requestFullScreen({
                direction: 0
            });
            this.fullScreen= true;
        },

        fullScreenChange(e) {
            if (!e.detail.fullScreen) {
                this.videoContext.stop();
                this.fullScreen= false;
            }
        },

        /* *********************** 语音相关start *********** */
        setupAudioPlayer() {
            this.innerAudioContext = uni.createInnerAudioContext();
            this.innerAudioContext.obeyMuteSwitch = false;
            this.innerAudioContext.onEnded((res) => {
                this.currentAudio.toolUse.is_ended = true;
                this.stopVoice();
            });
            this.innerAudioContext.onTimeUpdate(() => {
                if (!this.is_moving_slider) {
                    // 播放中
                    this.currentAudio = this.datalist[this.currentAudio.toolUse.listIndex].audioA[0];
                    let param = {};
                    let toolUsestr = 'datalist[' + this.currentAudio.toolUse.listIndex + '].audioA[0].toolUse';
                    let toolUse = this.currentAudio.toolUse;
                    toolUse['current_process'] = util.formatTime(this.innerAudioContext.currentTime);
                    toolUse['slider_value'] = Math.floor(this.innerAudioContext.currentTime);
                    toolUse['slider_max'] = Math.floor(this.innerAudioContext.duration);
                    param[toolUsestr] = toolUse;
                    this.setData(param);
                }
            });
        },

        // 拖动进度条，到指定位置
        hanle_slider_change(e) {
            const position = e.detail.value;
            this.seekCurrentAudio(position);
        },

        // 拖动进度条控件
        seekCurrentAudio(position) {
            this.innerAudioContext.seek(position);
        },

        // 进度条滑动
        handle_slider_move_start() {
            this.is_moving_slider= true;
        },

        handle_slider_move_end() {
            this.is_moving_slider= false;
        },

        // 点击播放暂停
        audio_play(e) {
            let listIndex = e.currentTarget.dataset.listindex;
            let postItem = this.datalist[listIndex];
            let currentAudio = postItem.audioA[0];
            this.currentAudio= currentAudio;
            var param = {};
            let audioset = 'datalist[' + listIndex + '].audioA[0].toolUse.currentAudio';
            param[audioset] = currentAudio.newUrl;
            let isplay = this.currentAudio.toolUse.is_play;
            let playstr = 'datalist[' + listIndex + '].audioA[0].toolUse.is_play';
            param[playstr] = !isplay;
            this.setData(param);

            if (isplay) {
                this.innerAudioContext.pause();
                isplay = false;
            } else {
                if (!isplay && !this.currentAudio.toolUse.is_ended) {
                    this.playVoice();
                } else {
                    this.innerAudioContext.play();
                }
            }
        },

        playVoice() {
            this.innerAudioContext.src = this.currentAudio.attachment;
            this.innerAudioContext.play();
        },

        stopVoice() {
            var param = {};
            let toolUsestr = 'datalist[' + this.currentAudio.toolUse.listIndex + '].audioA[0].toolUse';
            let toolUse = this.currentAudio.toolUse;
            toolUse['is_play'] = false;
            toolUse['slider_value'] = 0;
            toolUse['current_process'] = util.formatTime(0);
            param[toolUsestr] = toolUse;
            this.setData(param);
            this.innerAudioContext.stop();
            this.currentAudio = this.datalist[this.currentAudio.toolUse.listIndex].audioA[0];
        },

        /* *********************** 语音end *********** */
        lookImage(e) {
            let cellItem = this.datalist[e.currentTarget.dataset.cellindex];
            let imageA = cellItem.imageA;
            var imageSrcArray = [];

            for (let i = 0; i < imageA.length; i++) {
                let item = imageA[i];
                imageSrcArray.push(item.attachment);
            }

            uni.previewImage({
                current: imageSrcArray[e.currentTarget.id],
                urls: imageSrcArray
            });
        },

        navClick() {
            console.log('占位：函数 navClick 未声明');
        },

        listShare() {
            console.log('占位：函数 listShare 未声明');
        },

        disVoice() {
            console.log('占位：函数 disVoice 未声明');
        },

        discClick() {
            console.log('占位：函数 discClick 未声明');
        },

        playVideo() {
            console.log('占位：函数 playVideo 未声明');
        }
    }
};
</script>
<style>
@import './discovery.css';
</style>
